package com.haixee.parkdemo.common.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haixee.parkdemo.common.context.WebContextHolder;
import com.haixee.parkdemo.common.entity.AuthData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 验证：验证用户的身份
 *
 * @author GUIFENG GUO
 * 2020/3/22 9:26
 */
@Slf4j
@WebFilter(filterName = "AuthenticateFilter", urlPatterns = {"/*"})
@Order(value = Integer.MAX_VALUE - 200)
@Configuration
public class AuthenticateFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String uidData = request.getHeader("uid");
        if (StringUtils.isNotBlank(uidData)) {
            Integer uid = Integer.parseInt(uidData);
            WebContextHolder.setUid(uid);
        }

        String aclData = request.getHeader("authData");
        if (StringUtils.isNotBlank(aclData)) {
            ObjectMapper objectMapper = new ObjectMapper();
            AuthData authData = objectMapper.readValue(aclData, AuthData.class);
            WebContextHolder.setAuth(authData);
        }


        filterChain.doFilter(servletRequest, servletResponse);
    }

}
